package xyz.fefine;

import java.util.Arrays;

/**
 * Created by feng_ on 2016/9/2.
 * 表达式解析
 */
public class ExprParser {

    private Lexer lexer;

    ExprParser(Lexer lexer) {
        this.lexer = lexer;
    }

    public void token(String name) throws ParseException{
        Token token = lexer.read();
        if(!token.isIdentifier() || !token.getString().equals(name)){
            throw new ParseException(token);
        }
    }

    public boolean isToken(String name) throws ParseException{

        Token token = lexer.peek(0);    //判断后一个
        return token.isIdentifier() && name.equals(token.getString());

    }

    public ASTree expression() throws ParseException{
        ASTree tree = term();
        while (isToken("+") || isToken("-")) {
            ASTLeaf astLeaf = new ASTLeaf(lexer.read());
            ASTree asTree = term();
            tree = new BinaryExpr(Arrays.asList(tree,astLeaf,asTree));
        }
        return tree;
    }

    public ASTree term() throws ParseException{

        ASTree f = factory();
        while (isToken("*") || isToken("/")) {
            ASTLeaf astLeaf = new ASTLeaf(lexer.read());
            ASTree asTree = factory();
            f = new BinaryExpr(Arrays.asList(f,astLeaf,asTree));
        }
        return f;
    }

    public ASTree factory() throws ParseException{

        if(isToken("(")){
            token("(");
            ASTree e = expression();
            token(")");
            return e;
        }else{

            //数字
            Token t = lexer.read();
            if (t.isNumber()) {
                NumberLiteral numberLiteral = new NumberLiteral(t);
                return numberLiteral;
            }else{
                throw new ParseException(t);
            }

        }
    }

    public static void main(String[] args) throws ParseException{
        Lexer lexer = new Lexer(new CodeDialog());
        ExprParser parser = new ExprParser(lexer);
        ASTree t = parser.expression();
        System.out.println(t);
        //test success
    }

}
